<template>
  <div id='goods'>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="queryInfo.query" clearable @clear="getGoodsList">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="goAddPage">添加商品</el-button>
        </el-col>
      </el-row>
      <el-table :data="goodslist" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="商品名称" prop="goods_name"></el-table-column>
        <el-table-column label="商品价格（元）" prop="goods_price" width="120px"></el-table-column>
        <el-table-column label="商品重量" prop="goods_weight" width="80px"></el-table-column>
        <el-table-column label="创建时间" prop="add_time" width="160px">
          <template slot-scope="scope">
            {{ scope.row.add_time | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="190px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.goods_id)">编辑
            </el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeGood(scope.row.goods_id)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[5, 10, 20, 30]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" background>
      </el-pagination>
    </el-card>
    <el-dialog title="编辑商品信息" :visible="editGoodDialogVisible" @close="editGoodDialogVisible = false">
      <el-form :model="editGoodForm" label-width="90px" :rules="editFormRules" ref="editFormRef">
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="editGoodForm.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
          <el-input v-model="editGoodForm.goods_price" type="number" oninput="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight">
          <el-input v-model="editGoodForm.goods_weight" type="number" oninput="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_number">
          <el-input v-model="editGoodForm.goods_number" type="number" oninput="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"></el-input>
        </el-form-item>
        <el-form-item label="商品介绍" prop="goods_introduce">
          <el-input v-model="editGoodForm.goods_introduce"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editGood">确 定</el-button>
        <el-button @click="editGoodDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: 'goods',
    data() {
      return {
        // 查询参数对象
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 5
        },
        // 商品列表
        goodslist: [],
        // 总数据条数
        total: 0,
        // 控制编辑对话框的显示与隐藏
        editGoodDialogVisible: false,
        // 编辑商品数据
        editGoodForm: {},
        // 编辑商品的校验规则
        editFormRules: {
          goods_name: {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          },
          goods_price: {
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          },
          goods_weight: {
            required: true,
            message: '请输入商品重量',
            trigger: 'blur'
          },
          goods_number: {
            required: true,
            message: '请输入商品数量',
            trigger: 'blur'
          },
        }
      }
    },
    created() {
      this.getGoodsList()
    },
    methods: {
      // 根据分页获取对应的商品列表
      async getGoodsList() {
        // get请求要定义params属性
        await this.$http.get('goods', {
          params: this.queryInfo
        }).then(res => {
          if (res.data.meta.status === 200) {
            this.goodslist = res.data.data.goods
            this.total = res.data.data.total
          } else {
            this.$message({
              type: 'error',
              message: res.data.meta.msg,
              duration: 2000
            })
          }
        })
      },
      // 每页显示条数发送变化
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        this.getGoodsList()
      },
      // 当前页发生变化
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage
        this.getGoodsList()
      },
      // 删除商品
      async removeGood(id) {
        await this.$confirm("确定删除该商品吗？", "提示", {
          confirmText: '确定',
          cancleText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete(`goods/${id}`).then(res => {
            if (res.data.meta.status === 200) {
              this.$message({
                type: 'success',
                message: res.data.meta.msg,
                duration: 600
              })
              this.getGoodsList()
            } else {
              this.$message({
                type: 'error',
                message: res.data.meta.msg,
                duration: 2000
              })
            }
          })
        }).catch(err => {
          return err
        })
      },
      // 跳转到添加页面
      goAddPage() {
        this.$router.push('goods/add')
      },
      // 显示编辑对话框
      showEditDialog(id) {
        this.$http.get(`goods/${id}`).then(res => {
          if (res.data.meta.status === 200) {
            this.editGoodForm = res.data.data
            this.editGoodDialogVisible = true
          } else {
            this.$message({
              type: 'success',
              message: res.data.meta.mag,
              duration: 2000
            })
          }
        })
      },
      // 编辑商品
      editGood() {
        this.$refs.editFormRef.validate(async (valid) => {
          if (valid) {
            await this.$http.put(`goods/${this.editGoodForm.goods_id}`, this.editGoodForm).then(res => {
              if (res.data.meta.status === 200) {
                this.$message({
                  type: 'success',
                  message: '编辑商品成功！',
                  duration: 600
                })
                this.getGoodsList()
                this.editGoodDialogVisible = false
              } else {
                return this.$message({
                  type: 'error',
                  message: res.data.meta.msg,
                  duration: 2000
                })
              }
            })
          } else {
            return this.$message({
              type: 'error',
              message: '请输入表单必填项'
            })
          }
        })
      }
    },
  }

</script>
<style scoped>
</style>
